package com.qiang.consumer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.utils.FallbackMethod;
import com.qiang.consumer.controller.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    @HystrixCommand(fallbackMethod = "findAllFallback")
    public List<UserDto> findAll() {
        UserDto[] userDtos = restTemplate.getForObject("http://USERSERVICE/user/", UserDto[].class);
        return Arrays.asList(userDtos);
    }

    @Override
    @HystrixCommand(defaultFallback = "loadFallback")
    public UserDto load(Long id) {
        return this.restTemplate.getForEntity("http://USERSERVICE/users/" + id, UserDto.class).getBody();
    }

    protected List<UserDto> findAllFallback() {
        List<UserDto> userDtos = new ArrayList<>();
        userDtos.add(new UserDto("zhangsanFallback", 20));
        return userDtos;
    }

    protected UserDto loadFallback() {
        return new UserDto("lisiFallback", 23);
    }

    //服务隔离的颗粒度

}
